package gamemap

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)
func LoadAllMap() error {
	var err error
	Ascent,err=BaseLoad("./Ascent.mp")
	if err!=nil{
		log.Println("读取地图文件失败")
		return err
	}
	Ascent.Name="亚海悬城"
	return nil
}

func CreateEmptyMap(size int,name string,path string) *Bmap {
	m:=new(Bmap)
	m.Size=size
	m.path=path
	m.Name=name
	m.Blocks=make([][]BlkType,0,size)
	for i:=0;i<m.Size;i++{
		m.Blocks=append(m.Blocks,make([]BlkType, 0,m.Size))
		for j:=0;j<m.Size;j++{
			m.Blocks[i]=append(m.Blocks[i],Empty)
		}
	}
	return m
}

func BaseLoad(path string) (*Bmap,error) {
	m:=new(Bmap)
	m.path=path
	filr,err:=os.Open(path)
	if err!=nil{
		log.Println("打开地图文件失败")
		return nil,err
	}
	defer filr.Close()
	scanner:=bufio.NewScanner(filr)
	if !scanner.Scan() {  // 先调用 Scan() 读取第一行
    log.Println("无法读取第一行")
    return nil, fmt.Errorf("文件为空或读取失败")
	}
	line:=scanner.Text()
	m.Size,err=strconv.Atoi(line)
	if err!=nil{
		log.Println(err)	
		return nil,err
	}
	m.Blocks=make([][]BlkType,m.Size)
	for i:=0;i<m.Size;i++{
		m.Blocks[i]=make([]BlkType,m.Size)
		if !scanner.Scan() {
    	log.Println("无法读取地图数据")
    	return nil, fmt.Errorf("文件为空或读取失败")
		}
		line:=scanner.Text()
		s:=strings.Split(line," ")
		for in,k:=range s{
			if k==""{
				continue
			}
			num,ok:=strconv.Atoi(k)
			if ok!=nil{
				log.Println("地图数据错误")
				return nil,errors.New("地图数据错误")
			}
			m.Blocks[i][in]=BlkType(num)
		}
	}
	return m,nil
}

func WriteMap(m *Bmap) {
	s:=strconv.Itoa(m.Size)+"\n"
	for i:=0;i<20;i++{
		for j:=0;j<20;j++{
			s+=strconv.Itoa(int(m.Blocks[i][j]))+" "
		}
		s+="\n"
	}
	os.WriteFile(m.path,[]byte(s),0666)
}